/*
 * uart.c
 *
 *  Created on: 28 Jul 2011
 *      Author: bwm23
 */
#include "uart.h"



// Reads len bytes of data from uart at base, into buffer,
// returns the number of bytes read..
int read_uart(unsigned int base, char* buffer)
{
	int returnValue = 0;
	int loopCounter = 0;
	char dummyBuffer;

	// flags is somewhat empirical, as we are spoofing a file descriptor
	int flags = 1;
	altera_avalon_uart_state* sp = (altera_avalon_uart_state*)base;
	sp->base = (unsigned int)base;

	while(1)
	{
		altera_avalon_uart_read(&sp, &dummyBuffer, 0, flags);
		if ((dummyBuffer != 0x0D)|(dummyBuffer != 0x0A))
		{
			*buffer = dummyBuffer;
			buffer++;
		}

		if (dummyBuffer == 0x0D)
		{
			altera_avalon_uart_read(&sp, &dummyBuffer, 0, flags);
				if (dummyBuffer == 0x0A)
				{
					buffer++;
					*buffer = 0;
					return 1;
				}
		}
	}
}

// Writes len bytes of data from buffer into uart base,
// returns the number of bytes read..
int write_uart(unsigned int base, const char* buffer, int len)
{
	int returnValue  = 0;
	// flags is somewhat empirical, as we are spoofing a file descriptor
	int flags = 1;
	altera_avalon_uart_state* sp = (altera_avalon_uart_state*)base;
	sp->base = (unsigned int)base;
	returnValue = altera_avalon_uart_write(&sp, buffer, len, flags);

	return(returnValue);
}

int getTxLength(char* string)
{
	int index = 0;

	while ((string[index])!=0) index++;
	return index;
}

int blueToothTest()
{
	//write_uart(BT_UART, at, getTxLength(at));
}

int sendBT(const char tx, char* rx)
{
	  write_uart(UART_0_BASE, tx, getTxLength(tx));
	  read_uart(UART_0_BASE, &rx);
}

